from django.shortcuts import render

# Create your views here.
from django.views import View
from django import http
from apps.users.models import User
from django.contrib.auth import login
import logging,json,re
from django_redis import get_redis_connection
# 日志输出器
logger = logging.getLogger('django')


class RegisterView(View):
    """用户注册
    POST http://www.meiduo.site:8080/register/
    """
    def post(self,request):
        # 接收参数
        # request.body获取请求体中json原始数据
        json_bytes = request.body
        json_str = json_bytes.decode() # 转为json字符串
        json_dict = json.loads(json_str) # 转python标准为字典

        # json_dict = json.loads(request.body.decode()) 简写

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        sms_code_client = json_dict.get('sms_code')

        # 校验参数
        # 判断是否缺少必传参数
        if not all([username,password,mobile]):
            return http.JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        # 判断用户名是否满足格式要求
        if not re.match(r'[a-zA-Z0-9_-]{5,20}',username):
            return http.JsonResponse({'code':400,'errmsg':'用户名不满足格式'})

        # 判断密码是否满足格式要求
        if not re.match(r'[a-zA-Z0-9]{8,20}',password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码不满足格式'})

        # 判断两次密码是否一致
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次密码不一致'})

        # 判断手机号是否满足格式
        if not re.match(r'^1[3-7][0-9]{8}',mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '手机号不满足格式'})


        # 短信验证码是否正确
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s'%mobile)

        # 判断验证码是否过期
        if not sms_code_server:
            return http.JsonResponse({'code':400,'errmsg':'短信验证码已过期'})

        # 判断用户输入的验证码是否于服务器一致
        if sms_code_server.decode() != sms_code_client:
            return http.JsonResponse({'code':400,'errmsg':'短信验证码不一致'})

        # 判断是否勾选协议
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': '为勾选同意'})

        # 实现逻辑
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '数据存储失败'})

        # 保持状态
        # 记住当前用户登录，session机制
        # login()方法是django提供的用于登录状态保持
        # login('请求对象','')
        login(request,user)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})


class UsernameCountView(View):
    """判断用户名是否重复注册
    GET http://www.meiduo.site:8080/usernames/itcast/count/
    """
    def get(self,request,username):
        """
        查询用户名对应记录个数
        param(参数)：username:用户名
        return:JSON
        """
        try:# 查询数据库数据
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':'400','errmsg':'数据错误'})
        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """手机号重复注册
    GET http://www.meiduo.site:8000/mobiles/13711111111/count/
    """
    def get(self,request,mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400,'errmsg':'数据错误'})
        return http.JsonResponse({'code':0, 'errmsg':'OK', 'count':count})